from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
import pymysql
from elasticsearch import Elasticsearch
from datetime import datetime
from .models import search,click
from django.utils.datastructures import OrderedSet
import random
es=Elasticsearch("http://localhost:9200")
user_id=None

def getRecentRecord(username, num):
    history_list = []
    all_history = search.objects.filter(user_id_id=username).all()
    for history in all_history:
        history_list.append(history.keywords)
    history_list.reverse()
    title_list = list(set(history_list))
    if len(title_list) > num:
        title_list = title_list[:num]
    return title_list

def getfavor(username):
    title_list = getRecentRecord(username, 10)
    all_kind_list=['穿越','爽文','霸道','古代','现代','职场','悬疑','恐怖']
    if len(title_list) == 0:
        title_list=random.choice(all_kind_list) #如果没有查询历史，则随机推荐
    titles = "".join(title_list)
    return titles

def login(request,methods=['GET','POST']):
    conn = pymysql.connect(
        host="127.0.0.1",
        database="search_engine",
        user='root',
        password='1234',
        charset='utf8'
    )
    id = request.POST.get('id')
    password = request.POST.get('password')
    if id and password:
        with conn.cursor() as cursor:
            cursor.execute("SELECT password FROM userlist WHERE user_id = %s", [id])
            result=cursor.fetchall()
            if result==():
                return render(request,'login_page.html')
            else:
                if password == result[0][0]:
                    global user_id
                    user_id=id
                    history_list = getRecentRecord(id, 10)
                    favor_list=getfavor(id)
                    suggest_list = []
                    response = es.search(
                        index="novelindex",
                        doc_type="",
                        body={
                            "query": {
                                "multi_match": {
                                    "query": favor_list,
                                    "fields": ["book_name", "content_introduction"]
                                }
                            }
                        })
                    for hit in response['hits']['hits']:
                        hit_dict = {}
                        hit_dict['book_name'] = hit['_source']['book_name']
                        hit_dict['book_href'] = hit['_source']['book_href']
                        suggest_list.append(hit_dict)
                    print(suggest_list[0])
                    return render(request,'index.html',
                                  {
                                      'user_id':id,
                                      'history_list':history_list,
                                      'suggest_list0':suggest_list[0],
                                      'suggest_list1': suggest_list[1],
                                      'suggest_list2': suggest_list[2],
                                      'suggest_list3': suggest_list[3],
                                      'suggest_list4': suggest_list[4],
                                      'suggest_list5': suggest_list[5],
                                      'suggest_list6': suggest_list[6],
                                      'suggest_list7': suggest_list[7],
                                      'suggest_list8': suggest_list[8],
                                      'suggest_list9': suggest_list[9],
                                  })

                else:
                    return render(request,'login_page.html')
    else:
        return render(request, 'login_page.html')


def register(request,methods=['GET','POST']):
    conn = pymysql.connect(
        host="127.0.0.1",
        database="search_engine",
        user='root',
        password='1234',
        charset='utf8'
    )
    id=request.POST.get('id')
    password=request.POST.get('password')
    if id and password:
        with conn.cursor() as cursor:
            cursor.execute("SELECT user_id FROM userlist WHERE user_id = %s", [id])
            result=cursor.fetchall()
            if result==(): #创建用户
                cursor.execute("insert into userlist values(%s,%s)",(id,password))
                conn.commit()
                isregister='恭喜你，注册成功'
                return render(request,"register_page.html",{'isregisters':isregister})
            else: #已有用户
                isregister='用户已存在，注册失败'
                return render(request,'register_page.html',{'isregisters':isregister})

    return render(request,'register_page.html')

def ESsearch(request,methods=['GET','POST']):
    print(user_id)
    search_content=request.POST.get('searchcontent1')
    wildcard_content1=request.POST.get('searchcontent2')
    wildcard_content2 = request.POST.get('searchcontent2_2')
    phrase_content1=request.POST.get('searchcontent3')
    phrase_content2=request.POST.get('searchcontent3_2')
    regexp_content1=request.POST.get('searchcontent4')
    regexp_content2 = request.POST.get('searchcontent4_2')
    if search_content: #对输入内容进行查询
        suggest_list = []
        suggestions = es.search(
            index="novelindex",
            doc_type="",
            body={
                "suggest": {
                    "my-suggest": {
                        "text": search_content,
                        "completion": {
                            "field": "suggestion",
                            "fuzzy": {
                                "fuzziness": 2
                            },
                            "size": 8
                        }
                    }
                }
            }
        )
        title_set = OrderedSet()
        for match in suggestions['suggest']['my-suggest'][0]['options'][:5]:
            title_set.add(match['_source']["book_name"])
        for title in title_set:
            suggest_list.append(title)
        search.objects.create(keywords=search_content,time=datetime.now(),user_id_id=user_id)
        start_time = datetime.now()
        response = es.search(
            index="novelindex",
            doc_type="",
            body={
                "query": {
                    "multi_match": {
                        "query": search_content,
                        "fields": ["book_name", "content_introduction"]
                    }
                },
                "from": 0,
                "size": 7712,#num_per_page,
                "highlight": {
                    "pre_tags": ["<span class='keyWord' >"],
                    "post_tags": ['</span>'],
                    "fields": {
                        "book_name": {},
                        "content_introduction": {}
                    }
                }
            }
        )
        end_time = datetime.now()
        last_time = (end_time - start_time).total_seconds()
        total_nums = response['hits']['total']['value']
        hit_list = []
        for hit in response['hits']['hits']:
            hit_dict = {}
            if 'book_name' in hit['highlight']:
                # join:列表转字符串
                hit_dict['book_name'] = "".join(hit['highlight']['book_name'])
            else:
                hit_dict['book_name'] = hit['_source']['book_name']

            if 'content_introduction' in hit['highlight']:
                hit_dict['content_introduction'] = "".join(hit['highlight']['content_introduction'])
            else:
                hit_dict['content_introduction'] = hit['_source']['content_introduction']

            hit_dict['pagerank'] = hit['_source']['pagerank']
            hit_dict['book_href'] = hit['_source']['book_href']
            hit_dict['author_name'] = hit['_source']['author_name']
            hit_dict['novel_status'] = hit['_source']['novel_status']
            hit_dict['novel_size'] = hit['_source']['novel_size']
            hit_dict['novel_authority'] = hit['_source']['novel_authority']
            hit_dict['novel_format'] = hit['_source']['novel_format']
            hit_dict['download_address'] = hit['_source']['download_address']
            hit_dict['publish_time'] = hit['_source']['publish_time']
            hit_dict['score'] = hit['_score']
            hit_list.append(hit_dict)
        return render(request, "show_result.html", {
            "total_nums": total_nums,
            "all_hits": hit_list,
            "last_time": last_time,
            "suggest_titles": suggest_list,
        })

    elif wildcard_content1 and wildcard_content2:
        start_time = datetime.now()
        # print(wildcard_content2)
        # print(wildcard_content1)
        response = es.search(
            index="novelindex",
            doc_type="",
            body={
                "query": {
                    "wildcard": {
                        wildcard_content2:wildcard_content1,
                    }
                },
                "from": 0,
                "size": 7712,
            }
        )
        end_time = datetime.now()
        last_time = (end_time - start_time).total_seconds()
        total_nums = response['hits']['total']['value']
        hit_list = []
        for hit in response['hits']['hits']:
            hit_dict = {}
            hit_dict['book_name'] = hit['_source']['book_name']
            hit_dict['content_introduction'] = hit['_source']['content_introduction']
            hit_dict['pagerank'] = hit['_source']['pagerank']
            hit_dict['book_href'] = hit['_source']['book_href']
            hit_dict['author_name'] = hit['_source']['author_name']
            hit_dict['novel_status'] = hit['_source']['novel_status']
            hit_dict['novel_size'] = hit['_source']['novel_size']
            hit_dict['novel_authority'] = hit['_source']['novel_authority']
            hit_dict['novel_format'] = hit['_source']['novel_format']
            hit_dict['download_address'] = hit['_source']['download_address']
            hit_dict['publish_time'] = hit['_source']['publish_time']
            hit_dict['score'] = hit['_score']
            hit_list.append(hit_dict)
        return render(request, "show_result.html", {
            "total_nums": total_nums,
            "all_hits": hit_list,
            "last_time": last_time
        })

    elif phrase_content1 and phrase_content2:
        # print(phrase_content1)
        # print(phrase_content2)
        start_time = datetime.now()
        response = es.search(
            index="novelindex",
            doc_type="",
            body={
                "query": {
                    "match_phrase": {
                        phrase_content2: phrase_content1,
                    }
                },
                "from": 0,
                "size": 7712,
            }
        )
        end_time = datetime.now()
        last_time = (end_time - start_time).total_seconds()
        total_nums = response['hits']['total']['value']
        hit_list = []
        for hit in response['hits']['hits']:
            hit_dict = {}
            hit_dict['book_name'] = hit['_source']['book_name']
            hit_dict['content_introduction'] = hit['_source']['content_introduction']
            hit_dict['pagerank'] = hit['_source']['pagerank']
            hit_dict['book_href'] = hit['_source']['book_href']
            hit_dict['author_name'] = hit['_source']['author_name']
            hit_dict['novel_status'] = hit['_source']['novel_status']
            hit_dict['novel_size'] = hit['_source']['novel_size']
            hit_dict['novel_authority'] = hit['_source']['novel_authority']
            hit_dict['novel_format'] = hit['_source']['novel_format']
            hit_dict['download_address'] = hit['_source']['download_address']
            hit_dict['publish_time'] = hit['_source']['publish_time']
            hit_dict['score'] = hit['_score']
            hit_list.append(hit_dict)
        return render(request, "show_result.html", {
            "total_nums": total_nums,
            "all_hits": hit_list,
            "last_time": last_time
        })

    elif regexp_content1 and regexp_content2:
        start_time = datetime.now()
        response = es.search(
            index="novelindex",
            doc_type="",
            body={
                "query": {
                    "regexp": {
                        regexp_content2: regexp_content1,
                    }
                },
                "from": 0,
                "size": 7712,
            }
        )
        end_time = datetime.now()
        last_time = (end_time - start_time).total_seconds()
        total_nums = response['hits']['total']['value']
        hit_list = []
        for hit in response['hits']['hits']:
            hit_dict = {}
            hit_dict['book_name'] = hit['_source']['book_name']
            hit_dict['content_introduction'] = hit['_source']['content_introduction']
            hit_dict['pagerank'] = hit['_source']['pagerank']
            hit_dict['book_href'] = hit['_source']['book_href']
            hit_dict['author_name'] = hit['_source']['author_name']
            hit_dict['novel_status'] = hit['_source']['novel_status']
            hit_dict['novel_size'] = hit['_source']['novel_size']
            hit_dict['novel_authority'] = hit['_source']['novel_authority']
            hit_dict['novel_format'] = hit['_source']['novel_format']
            hit_dict['download_address'] = hit['_source']['download_address']
            hit_dict['publish_time'] = hit['_source']['publish_time']
            hit_dict['score'] = hit['_score']
            hit_list.append(hit_dict)
        return render(request, "show_result.html", {
            "total_nums": total_nums,
            "all_hits": hit_list,
            "last_time": last_time
        })
    else:
        return render(request, 'index.html')

def snapshot(request,methods=['GET','POST']):
    book_name = request.POST.get('book_name')
    author_name = request.POST.get('author_name')
    novel_status = request.POST.get('novel_status')
    novel_size = request.POST.get('novel_size')
    # novel_diversity = request.POST.get('novel_diversity')
    novel_authority = request.POST.get('novel_authority')
    novel_format = request.POST.get('novel_format')
    publish_time = request.POST.get('publish_time')
    download_address = request.POST.get('download_address')
    content_introduction = request.POST.get('content_introduction')
    print(book_name)
    print(content_introduction)
    return render(request,"snapshot.html",
                  {
                      'book_name':book_name,
                      'author_name': author_name,
                      'novel_status': novel_status,
                      'novel_size': novel_size,
                      # 'novel_diversity': novel_diversity,
                      'novel_authority': novel_authority,
                      'novel_format': novel_format,
                      'publish_time': publish_time,
                      'download_address': download_address,
                      'content_introduction': content_introduction,
                  })

